package com.ruoyi.common.utils.yaml;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;

import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Objects;

/**
 * yaml转换工具类
 *
 * @author Hack2003
 * @date 2024/4/1 15:04
 **/
public class YamlUtil {


    /**
     * 新增的 YAML 实例，用于保留原始 YAML 格式
      */
    private static final Yaml YAML_WITH_PRESERVED_STYLE;

    static {
        DumperOptions dumperOptions = new DumperOptions();

        // 设置 DumperOptions
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
        // 可选，如果您希望序列化的结果略微整洁一些，但请注意这可能会影响到原始流式风格
        dumperOptions.setPrettyFlow(true);

        // 创建 Yaml 实例并设置 DumperOptions
        YAML_WITH_PRESERVED_STYLE = new Yaml(dumperOptions);
    }
    /**
     * 将YAML内容转换为Map
     *
     * @param yamlContent YAML内容
     * @return Map
     */
    public static LinkedHashMap<String, Object> convertYamlToMap(String yamlContent) {
        try {
            return YAML_WITH_PRESERVED_STYLE.load(new StringReader(yamlContent));
        } catch (Exception e) {
            throw new YamlParseException("YAML内容转Map异常", e);
        }
    }
    /**
     * 将Map转换为YAML，保留原始格式
     *
     * @param map
     * @return
     */
    public static String convertMapToYamlWithPreservedStyle(LinkedHashMap<String, Object> map) {
        return YAML_WITH_PRESERVED_STYLE.dump(map);
    }

    /**
     * 获取嵌套Map中的值
     *
     * @param root 根Map
     * @param path 属性路径
     * @return Map<String, Object> 或 null
     */
    public static LinkedHashMap<String, Object> getNestedMap(LinkedHashMap<String, Object> root, String path) {
        String[] keys = path.split("\\.");
        LinkedHashMap<String, Object> current = root;

        for (int i = 0; i < keys.length; i++) {
            if (current instanceof LinkedHashMap) {
                current = (LinkedHashMap<String, Object>) current.get(keys[i]);
                if (Objects.isNull(current)) {
                    return null;
                }
            } else {
                // 如果中间节点不是Map类型，则返回null
                return null;
            }
        }
        // 这里无需额外的return语句，因为循环结束时会自动返回current的值
        return current;
    }

    /**
     * 自定义异常类
     */
    public static class YamlParseException extends RuntimeException {
        public YamlParseException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
